package com.llbnk.springcoding.util;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class ApolloUtils {

    @Autowired
    private ObjectMapper objectMapper;


    private Config config;

    @PostConstruct
    public void initApolloConfig(){
        config = ConfigService.getAppConfig();
    }


    public  <T> Map<String, T> getMap(String key, Class<T> clazz) {
        String jsonConfig = config.getProperty(key, null);
        if (jsonConfig == null) {
            log.error("Configuration not found for key: {}", key);
            return new HashMap<>();
        }
        try {
            return objectMapper.readValue(jsonConfig, objectMapper.getTypeFactory().constructMapType(Map.class, String.class, clazz));
        } catch (Exception e) {
            log.error("Error parsing JSON to Map: {}", e.getMessage());
            return new HashMap<>();
        }
    }
}
